import axios, { AxiosInstance } from 'axios';
import { elMessage, getStorage } from '../utils/util';
import { elMessageType, storageType } from '../model/enum';

const request: AxiosInstance = axios.create({
  timeout: 10000,
  baseURL: 'http://localhost:3000',
  withCredentials: true,
});

// 添加请求拦截器
request.interceptors.request.use(
  (config) => {
    //如果存在token，请求头携带token
    const token = getStorage(storageType.SESSION, 'token');
    if (token) {
      config.headers.Authorization = `${token}`;
    }
    return config;
  },
  (error) => {
    elMessage(elMessageType.ERROR, error.message);
  }
);

// 添加响应拦截器
request.interceptors.response.use(
  (response) => {
    //进行错误判断
    const code: string[] = ['401', '402', '403', '404', '500'];
    if (code.includes(response.data.code)) {
      elMessage(elMessageType.ERROR, '请求错误，请重试');
    }
    return response.data;
  },
  (error) => {
    elMessage(elMessageType.ERROR, error.message);
  }
);

export default request;
